package com.bjsxt.controller;

import cn.hutool.core.lang.Snowflake;
import com.bjsxt.domain.Market;
import com.bjsxt.domain.UserFavoriteMarket;
import com.bjsxt.model.R;
import com.bjsxt.service.MarketService;
import com.bjsxt.service.UserFavoriteMarketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/userFavorites")
public class UserFavoriteMarketController {

    @Autowired
private UserFavoriteMarketService userFavoriteMarketService;
            @Autowired
    private MarketService marketService;
            @Autowired
           private Snowflake snowflake;

    @PostMapping("/addFavorite")
        public R add(@RequestBody Market market){
        Long userId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());

        UserFavoriteMarket userFavoriteMarket = new UserFavoriteMarket();
        String symbol  = market.getSymbol();

       Market marketDb =    marketService.getMarkBySymbol(symbol);

        userFavoriteMarket.setId(snowflake.nextId());
        userFavoriteMarket.setUserId(userId);
        userFavoriteMarket.setMarketId(marketDb.getId());
        userFavoriteMarket.setType(market.getType().intValue());


        boolean save = userFavoriteMarketService.save(userFavoriteMarket);
        if(save){
            return R.ok();
        }
        return R.fail();


    }


    @DeleteMapping("/{symbol}")
    public R deleteFavoriteMarket(@PathVariable("symbol")String symbol){
        Market markBySymbol = marketService.getMarkBySymbol(symbol);
        Long userId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());

      boolean ok =   userFavoriteMarketService.deleteFavoriteMarket(markBySymbol.getId(),userId);

      if(ok){
          return R.ok();
      }
      return R.fail();

    }


}
